package cn.org.intelli.zffserver.service;

import cn.hutool.core.util.URLUtil;
import cn.org.intelli.zffserver.aop.AuthenticationTicket;
import cn.org.intelli.zffserver.entity.DataBaseV2Entity;
import cn.org.intelli.zffserver.entity.JobEntity;
import cn.org.intelli.zffserver.entity.ModelEntity;
import cn.org.intelli.zffserver.entity.ModelPeggingMapEntity;
import cn.org.intelli.zffserver.repository.DataBaseV2Repository;
import cn.org.intelli.zffserver.repository.JobRepository;
import cn.org.intelli.zffserver.repository.ModelPeggingMapRepository;
import cn.org.intelli.zffserver.repository.ModelRepository;
import cn.org.intelli.zffserver.util.HttpClient;
import cn.org.intelli.zffserver.util.ResultSetTransferUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;


@Service
public class ResultService {
    /*  33 */   private static final Logger log = LoggerFactory.getLogger(cn.org.intelli.zffserver.service.ResultService.class);

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private ModelRepository modelRepository;

    @Autowired
    private DataBaseV2Repository dataBaseV2Repository;

    @Autowired
    private ModelPeggingMapRepository modelPeggingMapRepository;

    @Autowired
    private HttpClient httpClient;

    @Value("${job.result.windowsDir}")
    private String windowsDir;
    @Value("${job.result.linuxDir}")
    private String linuxDir;
    @Value("${datastudio.ip}")
    private String dsIp;
    @Value("${datastudio.port}")
    private String dsPort;
    @Value("${datastudio.uri}")
    private String dsUri;
    /*  60 */   private final Map<String, String> rangeRule = new HashMap<>();

    public ResultService() {
        /*  63 */
        this.rangeRule.put("lt", "<");
        /*  64 */
        this.rangeRule.put("gt", ">");
        /*  65 */
        this.rangeRule.put("lte", "<=");
        /*  66 */
        this.rangeRule.put("gte", ">=");
    }

    public String generateResultExcelFileRdbms(String jobId) throws Exception {
        /*  70 */
        JSONObject result = queryResult(jobId, null, null, null);
        /*  71 */
        JSONArray resultMeta = result.getJSONArray("resultMeta");
        /*  72 */
        JSONArray data = result.getJSONObject("result").getJSONArray("resultData");

        /*  74 */
        List<String> columnSort = new ArrayList<>();
        /*  75 */
        List<List<String>> head = new ArrayList<>();
        /*  76 */
        for (int i = 0; i < resultMeta.size(); i++) {
            /*  77 */
            JSONObject atom = resultMeta.getJSONObject(i);
            /*  78 */
            String desc = atom.getString("desc");
            /*  79 */
            String columnName = atom.getString("columnName");
            /*  80 */
            List<String> head0 = new ArrayList<>();
            /*  81 */
            head0.add(desc);
            /*  82 */
            head.add(head0);
            /*  83 */
            columnSort.add(columnName);
        }

        /*  86 */
        List<List<String>> excelData = new ArrayList<>();
        /*  87 */
        for (int j = 0; j < data.size(); j++) {
            /*  88 */
            JSONObject atom = data.getJSONObject(j);
            /*  89 */
            List<String> value0 = new ArrayList<>();
            /*  90 */
            for (String key : columnSort) {
                /*  91 */
                value0.add(atom.getString(key));
            }
            /*  93 */
            excelData.add(value0);
        }

        /*  96 */
        String os = System.getProperty("os.name");
        /*  97 */
        String tmpdir = null;
        /*  98 */
        if (StringUtils.startsWith(os.toLowerCase(), "win")) {
            /*  99 */
            tmpdir = this.windowsDir;
        } else {
            /* 101 */
            tmpdir = this.linuxDir;
        }

        /* 104 */
        JobEntity job = this.jobRepository.findById(jobId).get();
        /* 105 */
        ModelEntity model = this.modelRepository.findById(job.getModelId()).get();

        /* 107 */
        String modelName = model.getModelName();
        /* 108 */
        String excelFileName = modelName + "_" + jobId + ".xlsx";
        /* 109 */
        String excelFilePath = tmpdir + File.separator + excelFileName;
        /* 110 */
        File file = new File(excelFilePath);
        /* 111 */
        if (file.exists()) {
            /* 112 */
            file.delete();
        }

        /* 115 */
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();

        /* 117 */
        WriteFont headWriteFont = new WriteFont();
        /* 118 */
        headWriteFont.setFontHeightInPoints(Short.valueOf((short) 13));
        /* 119 */
        headWriteCellStyle.setWriteFont(headWriteFont);

        /* 121 */
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        /* 122 */
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);


        /* 125 */
        EasyExcel.write(excelFilePath)
/* 126 */.registerWriteHandler(horizontalCellStyleStrategy)
/* 127 */.registerWriteHandler(new SimpleColumnWidthStyleStrategy(Integer.valueOf(15)))
/* 128 */.sheet("data").head(head).doWrite(excelData);
        /* 129 */
        return excelFileName;
    }


    public void downloadFile(String downloadFileName, HttpServletResponse response) {
        /* 138 */
        String osName = System.getProperty("os.name");
        /* 139 */
        String tmpdir = null;
        /* 140 */
        if (StringUtils.startsWith(osName.toLowerCase(), "win")) {
            /* 141 */
            tmpdir = this.windowsDir;
        } else {
            /* 143 */
            tmpdir = this.linuxDir;
        }
        /* 145 */
        String fileDir = tmpdir + File.separator + downloadFileName;

        /* 147 */
        File file = new File(fileDir);
        /* 148 */
        response.setContentType("application/force-download;charset=UTF-8");
        /* 149 */
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLUtil.encode(downloadFileName));
        /* 150 */
        byte[] buffer = new byte[1024];
        /* 151 */
        FileInputStream fis = null;
        /* 152 */
        BufferedInputStream bis = null;
        try {
            /* 154 */
            fis = new FileInputStream(file);
            /* 155 */
            bis = new BufferedInputStream(fis);
            /* 156 */
            ServletOutputStream servletOutputStream = response.getOutputStream();
            /* 157 */
            int len = 0;
            /* 158 */
            while ((len = bis.read(buffer)) > 0) {
                /* 159 */
                servletOutputStream.write(buffer, 0, len);
            }
            /* 161 */
            servletOutputStream.close();
            /* 162 */
        } catch (Exception e) {
            /* 163 */
            e.printStackTrace();
            /* 164 */
            log.error("@downloadFile: error is {}", e.getMessage());
        } finally {
            /* 166 */
            if (bis != null) {
                try {
                    /* 168 */
                    bis.close();
                    /* 169 */
                } catch (IOException e) {
                    /* 170 */
                    e.printStackTrace();
                }
            }
            /* 173 */
            if (fis != null) {
                try {
                    /* 175 */
                    fis.close();
                    /* 176 */
                } catch (IOException e) {
                    /* 177 */
                    e.printStackTrace();
                }
            }
        }
    }


    public JSONObject queryResult(String jobId, Integer page, Integer pageSize, JSONObject param) throws Exception {
        /* 212 */
        JobEntity job = this.jobRepository.findById(jobId).get();
        /* 213 */
        String modelId = job.getModelId();
        /* 214 */
        ModelEntity model = this.modelRepository.findById(modelId).get();
        /* 215 */
        String modelCode = model.getModelCode();
        /* 216 */
        String resultTableName = modelCode + "_RESULT";
        /* 217 */
        List<String> sqls = sqlRender(page, pageSize, resultTableName, param, jobId);
        /* 218 */
        JSONObject result = queryFromDB(sqls, jobId);

        /* 220 */
        JSONObject finalResult = new JSONObject();
        /* 221 */
        finalResult.put("resultMeta", JSON.parseArray(model.getResultMeta()));
        /* 222 */
        finalResult.put("result", result);
        /* 223 */
        finalResult.put("resultType", model.getModelType());


        /* 226 */
        if (StringUtils.equals(model.getModelType(), "graph")) {
            /* 227 */
            JSONArray resultData = result.getJSONArray("resultData");
            /* 228 */
            JSONArray transResultData = new JSONArray();
            /* 229 */
            for (int i = 0; i < resultData.size(); i++) {
                /* 230 */
                JSONObject oriAtom = resultData.getJSONObject(i);
                /* 231 */
                JSONObject transAtom = transJsonAtom(oriAtom);
                /* 232 */
                transResultData.add(transAtom);
            }

            /* 235 */
            result.put("resultData", transResultData);
        }

        /* 238 */
        List<ModelPeggingMapEntity> peggings = this.modelPeggingMapRepository.findAllByModelId(modelId);
        /* 239 */
        Set<String> set = new HashSet<>();
        /* 240 */
        peggings.forEach(pegging -> set.add(pegging.getColumnName()));
        /* 241 */
        result.put("resultPeggings", set);
        /* 242 */
        return finalResult;
    }

    private JSONObject transJsonAtom(JSONObject oriJson) {
        /* 246 */
        JSONObject transAtom = new JSONObject();
        /* 247 */
        JSONArray nodesArray = new JSONArray();
        /* 248 */
        JSONArray relationArray = new JSONArray();
        /* 249 */
        for (Map.Entry entry : oriJson.entrySet()) {
            /* 250 */
            String key = entry.getKey().toString();
            /* 251 */
            String value = oriJson.getString(key);
            /* 252 */
            if (isJsonArray(value).booleanValue()) {
                /* 253 */
                transAtom.put(key, JSON.parseArray(value));
                /* 254 */
            } else if (isJsonObject(value).booleanValue()) {
                /* 255 */
                transAtom.put(key, JSON.parseObject(value));
            } else {
                /* 257 */
                transAtom.put(key, value);
            }

            /* 260 */
            if (StringUtils.equals(key, "NODES")) {
                /* 261 */
                for (Map.Entry entry1 : oriJson.getJSONObject("NODES").entrySet()) {
                    /* 262 */
                    String cardNum = entry1.getKey().toString();
                    /* 263 */
                    nodesArray.add(oriJson.getJSONObject("NODES").getJSONObject(cardNum));
                }
            }
            /* 266 */
            if (StringUtils.equals(key, "RELATIONSHIPS")) {
                /* 267 */
                for (Map.Entry entry1 : oriJson.getJSONObject("RELATIONSHIPS").entrySet()) {
                    /* 268 */
                    String transId = entry1.getKey().toString();
                    /* 269 */
                    relationArray.add(oriJson.getJSONObject("RELATIONSHIPS").getJSONObject(transId));
                }
            }
        }
        /* 273 */
        transAtom.put("NODES", nodesArray);
        /* 274 */
        transAtom.put("RELATIONSHIPS", relationArray);
        /* 275 */
        return transAtom;
    }

    private Boolean isJsonArray(String str) {
        try {
            /* 280 */
            JSON.parseArray(str);
            /* 281 */
            return Boolean.valueOf(true);
            /* 282 */
        } catch (Exception e) {
            /* 283 */
            return Boolean.valueOf(false);
        }
    }

    private Boolean isJsonObject(String str) {
        try {
            /* 289 */
            JSON.parseObject(str);
            /* 290 */
            return Boolean.valueOf(true);
            /* 291 */
        } catch (Exception e) {
            /* 292 */
            return Boolean.valueOf(false);
        }
    }


    private JSONObject queryFromDB(List<String> sqls, String jobId) throws Exception {
        /* 305 */
        JobEntity jobEntity = this.jobRepository.findById(jobId).get();
        /* 306 */
        String destinationDbSourceId = jobEntity.getDestinationDbId();
        /* 307 */
        DataBaseV2Entity db = this.dataBaseV2Repository.findById(destinationDbSourceId).get();

        /* 309 */
        JSONObject dbInfo = JSON.parseObject(db.getDbInfo());

        /* 311 */
        String driverName = dbInfo.getString("driverName");
        /* 312 */
        String dbUrl = dbInfo.getString("dbUrl");
        /* 313 */
        String dbUserName = dbInfo.getString("dbUserName");
        /* 314 */
        String dbPassword = dbInfo.getString("dbPassword");


        /* 317 */
        String sql = sqls.get(0);
        /* 318 */
        String countSql = sqls.get(1);

        /* 320 */
        Connection conn = null;
        /* 321 */
        Statement smt = null;
        try {
            /* 323 */
            Class.forName(driverName);
            /* 324 */
            conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
            /* 325 */
            smt = conn.createStatement();
            /* 326 */
            ResultSet rs = smt.executeQuery(sql);
            /* 327 */
            JSONArray resultJson = ResultSetTransferUtil.resultSetToJson(rs);

            /* 329 */
            ResultSet countRs = smt.executeQuery(countSql);
            /* 330 */
            JSONArray countResultJson = ResultSetTransferUtil.resultSetToJson(countRs);
            /* 331 */
            Integer totalNum = countResultJson.getJSONObject(0).getInteger("crs_total_num");

            /* 333 */
            JSONObject result = new JSONObject();
            /* 334 */
            result.put("resultData", resultJson);
            /* 335 */
            result.put("resultTotalNum", totalNum);

            /* 337 */
            return result;
            /* 338 */
        } catch (Exception e) {
            /* 339 */
            e.printStackTrace();
            /* 340 */
            throw new Exception(e);
        } finally {
            /* 342 */
            smt.close();
            /* 343 */
            conn.close();
        }
    }


    private List<String> sqlRender(Integer page, Integer pageSize, String tableName, JSONObject param, String jobId) {
        /* 359 */
        JobEntity jobEntity = this.jobRepository.findById(jobId).get();
        /* 360 */
        String destinationDbSourceId = jobEntity.getDestinationDbId();
        /* 361 */
        DataBaseV2Entity db = this.dataBaseV2Repository.findById(destinationDbSourceId).get();

        /* 363 */
        JSONObject dbInfo = JSON.parseObject(db.getDbInfo());
        /* 364 */
        String shcemaName = dbInfo.getString("schemaName");
        /* 365 */
        List<String> sqls = new ArrayList<>();

        /* 367 */
        StringBuffer sb = new StringBuffer();
        /* 368 */
        StringBuffer countSb = new StringBuffer();
        /* 369 */
        sb.append("SELECT * FROM " + shcemaName + "." + tableName + "\n");
        /* 370 */
        countSb.append("SELECT count(0) as crs_total_num FROM " + shcemaName + "." + tableName + "\n");
        /* 371 */
        sb.append("WHERE 1=1\n");
        /* 372 */
        countSb.append("WHERE 1=1\n");

        /* 374 */
        sb.append("AND JOBID = '" + jobId + "'\n");
        /* 375 */
        countSb.append("AND JOBID = '" + jobId + "'\n");

        /* 377 */
        if (param != null && param.size() > 0) {
            /* 378 */
            for (Map.Entry entry : param.entrySet()) {
                /* 379 */
                JSONObject ruleValue;
                String key = entry.getKey().toString();
                /* 380 */
                JSONObject rule = param.getJSONObject(key);
                /* 381 */
                String type = rule.getString("type");
                /* 382 */
                switch (type) {
                    case "equal":
                        /* 384 */
                        sb.append("AND " + key + " = '" + rule.getString("value") + "' \n");
                        /* 385 */
                        countSb.append("AND " + key + " = '" + rule.getString("value") + "' \n");

                    case "like":
                        /* 388 */
                        sb.append("AND " + key + " like '%" + rule.getString("value") + "%' \n");
                        /* 389 */
                        countSb.append("AND " + key + " like '%" + rule.getString("value") + "%' \n");

                    case "range":
                        /* 392 */
                        ruleValue = rule.getJSONObject("value");
                        /* 393 */
                        for (Map.Entry ruleEntry : ruleValue.entrySet()) {
                            /* 394 */
                            String rangeKey = ruleEntry.getKey().toString();
                            /* 395 */
                            String rangeValue = ruleValue.getString(rangeKey);
                            /* 396 */
                            sb.append("AND " + key + " " + this.rangeRule.get(rangeKey) + " '" + rangeValue + "' \n");
                            /* 397 */
                            countSb.append("AND " + key + " " + this.rangeRule.get(rangeKey) + " '" + rangeValue + "' \n");
                        }
                }

            }
        }
        /* 403 */
        if (page != null && pageSize != null) {
            /* 404 */
            Integer offset = Integer.valueOf((page.intValue() - 1) * pageSize.intValue());
            /* 405 */
            sb.append("LIMIT " + offset + ", " + pageSize + "\n");
        }
        /* 407 */
        sqls.add(sb.toString());
        /* 408 */
        sqls.add(countSb.toString());
        /* 409 */
        return sqls;
    }


    public JSONObject resultPegging(String modelId, String columnName, JSONObject rowData, Integer page, Integer pageSize, String jobId) throws Exception {
        /* 428 */
        ModelPeggingMapEntity ds = this.modelPeggingMapRepository.findFirstByModelIdAndColumnNameAndScriptType(modelId, columnName, "DATA");

        /* 430 */
        ModelPeggingMapEntity dcs = this.modelPeggingMapRepository.findFirstByModelIdAndColumnNameAndScriptType(modelId, columnName, "COUNT");
        /* 431 */
        if (ds == null || dcs == null) {
            /* 432 */
            throw new Exception("当前模型、属性未建立数据反查绑定关系");
        }
        /* 434 */
        Map<String, String> headers = new HashMap<>();
        /* 435 */
        headers.put("Content-Type", "application/json");
        /* 436 */
        headers.put("x-consumer-username", AuthenticationTicket.getTicket().getPin());

        /* 438 */
        JSONObject requestBody = new JSONObject();


        /* 441 */
        for (Map.Entry entry : rowData.entrySet()) {
            /* 442 */
            String key = entry.getKey().toString();
            /* 443 */
            String value = rowData.getString(key);
            /* 444 */
            if (checkJsonObject(value).booleanValue()) {
                /* 445 */
                rowData.put(key, JSON.parseObject(value));
            }
        }
        /* 448 */
        requestBody.putAll(rowData);

        /* 450 */
        requestBody.put("PAGE", page);
        /* 451 */
        requestBody.put("PAGESIZE", pageSize);

        /* 453 */
        JobEntity jobInfo = this.jobRepository.findById(jobId).get();
        /* 454 */
        if (StringUtils.isNotEmpty(jobInfo.getParam())) {
            /* 455 */
            JSONObject jobParams = JSONObject.parseObject(jobInfo.getParam());
            /* 456 */
            requestBody.putAll(jobParams);
        }

        /* 459 */
        JSONObject params = new JSONObject();
        /* 460 */
        params.put("params", requestBody);

        /* 462 */
        Integer totalNum = Integer.valueOf(0);
        /* 463 */
        String countUri = this.dsUri + dcs.getScriptId();

        /* 465 */
        String countStr = this.httpClient.post(countUri, params, this.dsIp, this.dsPort, headers, null);

        /* 467 */
        if (StringUtils.isEmpty(countStr)) {
            /* 468 */
            throw new Exception("反查出问题了");
        }
        /* 470 */
        JSONObject countJson = JSON.parseObject(countStr);
        /* 471 */
        if (!countJson.getBoolean("status").booleanValue()) {
            /* 472 */
            throw new Exception(countJson.getString("message"));
        }

        /* 475 */
        totalNum = countJson.getJSONObject("data").getJSONArray("data").getJSONObject(0).getInteger("NUM");

        /* 477 */
        String dataUri = this.dsUri + ds.getScriptId();

        /* 479 */
        String dataStr = this.httpClient.post(dataUri, params, this.dsIp, this.dsPort, headers, null);

        /* 481 */
        if (StringUtils.isEmpty(dataStr)) {
            /* 482 */
            throw new Exception("反查出问题了");
        }
        /* 484 */
        JSONObject dataJson = JSON.parseObject(dataStr);
        /* 485 */
        System.out.println(dataJson);
        /* 486 */
        if (!dataJson.getBoolean("status").booleanValue()) {
            /* 487 */
            throw new Exception(dataJson.getString("message"));
        }

        /* 490 */
        JSONArray peggingData = dataJson.getJSONObject("data").getJSONArray("data");

        /* 492 */
        JSONObject result = new JSONObject();
        /* 493 */
        result.put("peggingData", peggingData);
        /* 494 */
        result.put("totalNum", totalNum);

        /* 496 */
        return result;
    }

    private Boolean checkJsonObject(String str) {
        try {
            /* 501 */
            JSON.parseObject(str);
            /* 502 */
            return Boolean.valueOf(true);
            /* 503 */
        } catch (Exception e) {
            /* 504 */
            return Boolean.valueOf(false);
        }
    }
}


/* Location:              C:\Users\admin\Desktop\xxm\zjg11\ZjgCaculate-v1.0.jar!\BOOT-INF\classes\cn\org\intelli\zffserver\service\ResultService.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */